﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Routing;
using VQWEB.administrator.sources;
using System.Web.Script.Serialization;
using VQWEB.common;
using VQData;
namespace VQWEB.administrator.handlers
{
    /// <summary>
    /// Summary description for ExcerciseHandler
    /// </summary>
    public class eng_ExcerciseHandler : IHttpHandler,IRouteHandler
    {
        EnglishData EnglishData = new EnglishData();
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        public void ProcessRequest(HttpContext context)
        {
            #region Excercise     
            string add_excercise = context.Request["add_excercise"];
            if (!string.IsNullOrEmpty(add_excercise))
            {
                BusinessLayer<EnglishModelDataContext> bussiness = new BusinessLayer<EnglishModelDataContext>();
                var obj = bussiness.InsertOrUpdate<eng_excercise>(add_excercise);
               context.Response.Write("Success Full");
            }

            string list_excercise = context.Request["list_excercise"];
            if(!string.IsNullOrEmpty(list_excercise)){
                RenderExcercise(context);
            }

            string view_excercise = context.Request["view_excercise"];
            if (!string.IsNullOrEmpty(view_excercise))
            {
                string Id = context.Request["Id"];
                RenderSingleExcercise(context, Convert.ToInt32(Id));
            }

            string delete_excercise = context.Request["delete_excercise"];
            if (!string.IsNullOrEmpty(delete_excercise)) {
                BusinessLayer<EnglishModelDataContext> bussiness = new BusinessLayer<EnglishModelDataContext>();
                bussiness.Delete<eng_excercise>(delete_excercise);
                RenderExcercise(context);
            }
            string lockunlock_excercise = context.Request["lockunlock_excercise"];
            if (!string.IsNullOrEmpty(lockunlock_excercise)) {
                BusinessLayer<EnglishModelDataContext> bussiness = new BusinessLayer<EnglishModelDataContext>();
                bussiness.LockUnLock<eng_excercise>(lockunlock_excercise, "excercise_active");
                RenderExcercise(context);
            }
            #endregion

            #region Excercise Group
            string add_excercise_group = context.Request["add_excercise_group"];
            if (!string.IsNullOrEmpty(add_excercise_group))
            {
                BusinessLayer<EnglishModelDataContext> bussiness = new BusinessLayer<EnglishModelDataContext>();
                var obj = bussiness.InsertOrUpdate<eng_excercises_group>(add_excercise_group);
                bussiness.InsertAllInOne<eng_group_excercise>(obj.excercise_array_id, "excerise_id", "group_excercise_id", obj.group_excercise_id);
               context.Response.Write("Success Full");

            }
            string view_excercise_group = context.Request["view_excercise_group"];
            if (!string.IsNullOrEmpty(view_excercise_group))
            {
                string Id = context.Request["Id"];
                RenderSingleExcerciseGroup(context, Convert.ToInt32(Id));
            }
            string list_excercise_group = context.Request["list_excercise_group"];
            if (!string.IsNullOrEmpty(list_excercise_group))
            {
                RenderExcerciseGroup(context);
            }
            string delete_excercise_group = context.Request["delete_excercise_group"];
            if (!string.IsNullOrEmpty(delete_excercise_group))
            {
                BusinessLayer<EnglishModelDataContext> bussiness = new BusinessLayer<EnglishModelDataContext>();
                bussiness.Delete<eng_excercises_group>(delete_excercise_group);
                RenderExcerciseGroup(context);
            }
            string lockunlock_excercise_group = context.Request["lockunlock_excercise_group"];
            if (!string.IsNullOrEmpty(lockunlock_excercise_group))
            {
               BusinessLayer<EnglishModelDataContext> bussiness = new BusinessLayer<EnglishModelDataContext>();
               bussiness.LockUnLock<eng_excercises_group>(lockunlock_excercise_group, "excercise_active");
                RenderExcerciseGroup(context);
            }
            #endregion


            string result = context.Request["result"];
            if (!string.IsNullOrEmpty(result)) {
               //Serializer from client list result
                List<Dictionary<string, string>> list_result = serializer.Deserialize<List<Dictionary<string, string>>>(result);
                string  sid = context.Request["array_id"];            
                List<int> array_id = serializer.Deserialize<List<int>>(sid);               
                //Query answer from database list answer
                List<Dictionary<string,string>> list_answer = new List<Dictionary<string,string>>();
                Dictionary<int, string> dic = EnglishData.ViewAnswerExcercise(array_id);
                foreach (KeyValuePair<int,string> item in dic)
                {
                    Dictionary<string, string> dic_answer = ViewAnswerDictionary(item.Key, item.Value);
                    list_answer.Add(dic_answer);
                }

                //Compare clien & database
                string sResponse = "So cau tra loi dung la: \n";
                int i = 1;
                foreach (var question in list_result)
                {
                    bool flag = false;
                    foreach (var answer in list_answer)
                    {
                        flag = HelperData.DictionaryEqualExcercise(answer, question);
                        if (flag == true)
                            sResponse += "Cau: " + i + " Tra loi dung\n";                       
                    }
                    i++;
                }
                context.Response.Write(sResponse);
            }
           
        }
        private void RenderSingleExcercise(HttpContext context, int Id)
        {
            DataLayer<EnglishModelDataContext> layer = new DataLayer<EnglishModelDataContext>();
            object obj = layer.Get<eng_excercise>(
               c => c.excercise_id.Equals(Id),
               c => new
               {
                   id = c.excercise_id,
                   typecode = c.type_code,
                   file=c.excercise_file,
                   title = c.excercise_title,
                   content=c.excercise_content,
                   answer=c.excercise_answer,
                   explain=c.excercise_explain,
                   active = c.excercise_active
               });
            string json = serializer.Serialize(obj);
            context.Request.ContentType = "application/json";
            context.Response.Write(json);
        }
       
         private void RenderExcercise(HttpContext context) {
             DataLayer<HuongNghiepModelDataContext> layer = new DataLayer<HuongNghiepModelDataContext>();
             IList<object> list = layer.List<eng_excercise>(
                 null,
                 null,
                 null,
                 c => c.excercise_title,
                  c => new
               {
                   id = c.excercise_id,
                   typecode = c.type_code,
                   file = c.excercise_file,
                   title = c.excercise_title,
                   content = c.excercise_content,
                   answer = c.excercise_answer,
                   explain = c.excercise_explain,
                   active = c.excercise_active
               });
             string json = serializer.Serialize(list);
             context.Request.ContentType = "aplication/json";
             context.Response.Write(json);
            
        }

         private void RenderSingleExcerciseGroup(HttpContext context, int Id)
         {
             DataLayer<EnglishModelDataContext> layer = new DataLayer<EnglishModelDataContext>();
             object obj = layer.Get<eng_excercises_group>(
                c => c.group_excercise_id.Equals(Id),
                c => new
                {
                    id = c.group_excercise_id,
                    typecode = c.type_code,
                    file = c.group_excercise_file,
                    title = c.group_excercise_title,
                    contentfirst = c.group_excercise_content_first,
                    contentlast = c.group_excercise_content_last,
                    active = c.group_excercise_active
                });
             string json = serializer.Serialize(obj);
             context.Request.ContentType = "application/json";
             context.Response.Write(json);

         }

         private void RenderExcerciseGroup(HttpContext context)
         {
             DataLayer<HuongNghiepModelDataContext> layer = new DataLayer<HuongNghiepModelDataContext>();
             IList<object> list = layer.List<eng_excercises_group>(
                 null,
                 null,
                 null,
                 c => c.group_excercise_title,
                  c => new
                  {
                      id = c.group_excercise_id,
                      typecode = c.type_code,
                      file = c.group_excercise_file,
                      title = c.group_excercise_title,
                      contentfirst = c.group_excercise_content_first,
                      contentlast = c.group_excercise_content_last,
                      active = c.group_excercise_active
                  });
             string json = serializer.Serialize(list);
             context.Request.ContentType = "aplication/json";
             context.Response.Write(json);
            
         }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private Dictionary<string, string>ViewAnswerDictionary(int excercise_id, string answer)
        { 

            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("excercise_id", excercise_id.ToString());
            string[] array = answer.Split(';');
            array = array.Where(x => !string.IsNullOrEmpty(x)).ToArray();
            foreach (string item in array)
            {

                if (item.Contains("="))
                {
                    string key = item.Substring(0, item.IndexOf("=")).Trim().ToLower();
                    string value = item.Substring(item.IndexOf("=") + 1).Trim().ToLower();
                    if (!dic.ContainsKey(key))
                        dic.Add(key, value);

                }
                else
                {
                    string key2 = item.Trim().ToLower();
                    string value2 = item.Trim().ToLower();
                    if (!dic.ContainsKey(key2))
                        dic.Add(key2, value2);

                }
            }

            return dic;
        }

        public IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            return this;
        }
    }
}